<template>
  <div class="dust-selection-dialog">
    <div class="hazards-content" v-loading="loading">
      <template v-if="hazardsList.length > 0">
        <div class="search-bar">
          <el-input
            v-model="searchQuery"
            size="small"
            clearable
            placeholder="支持中文模糊或首字母搜索（如：S）"
          />
        </div>

        <div class="hazards-tags" v-if="filteredHazards.length > 0">
        <el-tag
          v-for="hazard in filteredHazards"
          :key="hazard.id"
          size="small"
          class="hazard-tag"
          :class="{ 'is-selected': selectedHazard?.id === hazard.id }"
          @click="selectHazard(hazard)"
          @dblclick="selectHazard(hazard)"
        >
          {{ hazard.cnName }}
        </el-tag>
        </div>

        <div v-else-if="!loading" class="empty-state">
          <el-empty description="无匹配结果" :image-size="80" />
        </div>
      </template>
      <div v-else-if="!loading" class="empty-state">
        <el-empty description="暂无粉尘数据" :image-size="80" />
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, ref, computed } from 'vue'
import { ElMessage, ElTag, ElEmpty, ElInput } from 'element-plus'
import { HazardsApi, type HazardsVO } from '@/api/system/hazards'

// 定义事件
const emit = defineEmits(['hazard-selected'])

// 响应式数据
const loading = ref(false)
const hazardsList = ref<HazardsVO[]>([])
const selectedHazard = ref<HazardsVO | null>(null)
const searchQuery = ref('')

// 本地过滤后的粉尘列表
const filteredHazards = computed(() => {
  const query = searchQuery.value.trim().toLowerCase()
  if (!query) return hazardsList.value
  return hazardsList.value.filter((h) => {
    const cnName = (// @ts-ignore 兼容可能存在的英文字段
      h.cnName || ''
    ).toLowerCase()
    const letter = (// @ts-ignore 兼容可能存在的编码字段
      h.letter || ''
    ).toLowerCase()
    console.log(query, cnName, letter)
    return (
      cnName.includes(query)|| letter.includes(query)
    )
  })
})

// 加载粉尘数据
const loadHazards = async () => {
  try {
    loading.value = true
    const params = {
      pageNo: 1,
      pageSize: 999,
      type: '3',
      letter: ''
    }

    const response = await HazardsApi.getHazardsPage(params)
    console.log('粉尘数据:', JSON.stringify(response.list, null, 2))
    hazardsList.value = response.list || []
  } catch (error) {
    console.error('加载粉尘数据出错:', error)
    ElMessage.error('加载粉尘数据出错')
  } finally {
    loading.value = false
  }
}

// 选择粉尘
const selectHazard = (hazard: HazardsVO) => {
  console.log('选择的粉尘:', hazard)
  selectedHazard.value = hazard
  ElMessage.success(`已选择: ${hazard.cnName}`)
  // 触发父组件事件
  emit('hazard-selected', hazard)
}

// 组件挂载时加载数据
onMounted(() => {
  loadHazards()
})

</script>

<style lang="scss" scoped>
.dust-selection-dialog {
  padding: 0;
  max-height: 60vh;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.dialog-header {
  text-align: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.dialog-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 8px 0;
  line-height: 1.4;
}

.dialog-subtitle {
  font-size: 14px;
  color: #909399;
  margin: 0;
  line-height: 1.4;
}

.hazards-content {
  flex: 1;
  overflow-y: auto;
  padding-right: 8px;
  padding-left: 2px;

  // 自定义滚动条
  &::-webkit-scrollbar {
    width: 6px;
  }

  &::-webkit-scrollbar-track {
    background: #f5f5f5;
    border-radius: 3px;
  }

  &::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 3px;

    &:hover {
      background: #a8a8a8;
    }
  }
}

.hazards-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  align-items: flex-start;
  padding: 4px 0 8px 0;
}

.hazard-tag {
  cursor: pointer;
  transition: all 0.2s ease;
  font-size: 13px;
  padding: 6px 12px;
  border-radius: 16px;
  font-weight: 500;
  color: #e6a23c;
  background-color: #fdf6ec;
  border-color: #faecd8;
  border: 1px solid #faecd8;

  &:hover {
    transform: translateY(-1px);
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.12);
    background-color: #faecd8;
    border-color: #e6a23c;
  }

  &:active {
    transform: translateY(0);
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  }

  &.is-selected {
    color: #e6a23c;
    background-color: #faecd8;
    border-color: #e6a23c;
  }
}

.empty-state {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 200px;
  color: #909399;

  :deep(.el-empty__description) {
    color: #909399;
    font-size: 14px;
  }
}

// 加载状态样式优化
:deep(.el-loading-mask) {
  background-color: rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(2px);
}

// 搜索栏样式（更紧凑）
.search-bar {
  position: sticky;
  top: 0;
  z-index: 2;
  background: #fff;
  padding: 6px 0 8px 0;
  margin-bottom: 6px;
  border-bottom: 1px solid #f5f5f5;

  :deep(.el-input) {
    width: 100%;
  }

  :deep(.el-input__wrapper) {
    padding: 0 8px;
    min-height: 28px;
    box-shadow: none;
    border: 1px solid #ebeef5;
    border-radius: 8px;

    &:hover {
      border-color: #dcdfe6;
    }

    &.is-focus {
      border-color: #409eff;
      box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
    }
  }

  :deep(.el-input__inner) {
    font-size: 12px;
  }

  :deep(.el-input__prefix),
  :deep(.el-input__suffix) {
    color: #c0c4cc;
  }
}
</style>
